import BasePanel from "../BasePanel";
import TaskItem from "./TaskItem";

const {ccclass, property} = cc._decorator;

@ccclass
export default class TaskPanel extends BasePanel {
    @property(cc.Prefab)
    taskPrefab:cc.Prefab=null    
    private prefabParent:cc.Node;
    private layout:cc.Layout;
    private widget:cc.Widget;
    onLoad(){
        this.close;
        this.prefabParent = this.node.getChildByName("scrollview").getChildByName("view").getChildByName("content");
        this.layout = this.prefabParent.getComponent(cc.Layout);
        this.widget = this.prefabParent.getComponent(cc.Widget);
        QM.game.on("task",this.updateUI,this);
    }

    start(){
        this.node.active = false;
    }

    firstCall(){
        if(!this.isFirst) {
            this.layout.updateLayout();
            this.widget.updateAlignment();  
            return;
        };
        this.isFirst = false;
        var tasks = QM.game.getTaskAll();
        for(let taskId in tasks){
            var taskItem = cc.instantiate(this.taskPrefab);
            taskItem.parent = this.prefabParent;
            var com = taskItem.getComponent(TaskItem);
            com.state = tasks[taskId];
            com.taskId = Number(taskId);
        }        
        this.layout.updateLayout();
        this.widget.updateAlignment();
    }
    /** 变更任务状态或新增任务 */
    updateUI(event:QM.QEvent){        
        var taskId = event.data.id;
        var state = event.data.state;

        var node = this.prefabParent.getChildByName(taskId);
        if(!node){
            node = cc.instantiate(this.taskPrefab);
            node.parent = this.prefabParent;
        }
        var com = node.getComponent(TaskItem);        
        com.state = state;
        com.taskId = Number(taskId);   
        this.layout.updateLayout();
        this.widget.updateAlignment();             
    }

    /** 注销事件 */
    onDestroy(){
        QM.game.off("task");
    }
}
